package com.zz.framework.widget

import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Context
import android.content.DialogInterface
import android.graphics.Color
import android.graphics.drawable.AnimationDrawable
import android.graphics.drawable.ColorDrawable
import android.media.MediaPlayer
import android.media.MediaRecorder
import android.os.Environment
import android.os.Handler
import android.os.Message
import android.util.AttributeSet
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.widget.AppCompatButton
import com.zz.framework.R
import com.zz.framework.core.utils.LogUtils.error
import com.zz.framework.core.utils.NoiseFilteredRecorder
import com.zz.framework.core.utils.ZCountDownTimer
import com.zz.framework.core.utils.file.sandbox.FileAccessFactory.Companion.mFile
import java.io.File

/**
 * @version: V1.0
 * 带录音功能的button
 */
class RecordButton @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : AppCompatButton(context, attrs, defStyleAttr) {
    private var finishedListener: OnFinishedRecordListener? = null

    /**
     * 最短录音时间
     */
    private val MIN_INTERVAL_TIME = 1000

    /**
     * 最长录音时间
     */
    private val MAX_INTERVAL_TIME = 1000 * 61
    private var mStateTV: TextView? = null
    private var mStateIV: ImageView? = null
    private var mRecorder: NoiseFilteredRecorder = NoiseFilteredRecorder()
    private var volumeHandler: Handler? = null
    private var y = 0f

    fun setOnFinishedRecordListener(listener: OnFinishedRecordListener?) {
        finishedListener = listener
    }

    private var recordDialog: Dialog? = null

    init {
        init()
    }

    @SuppressLint("HandlerLeak")
    private fun init() {
        volumeHandler = object : Handler() {
            override fun handleMessage(msg: Message) {
                if (msg.what == -100) {
                    stopRecording()
                    recordDialog?.dismiss()
                } else if (msg.what != -1) {
                    mStateIV?.setImageResource(res[msg.what])
                }
            }
        }
    }

    private var anim: AnimationDrawable? = null

    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(event: MotionEvent): Boolean {
        val action = event.getAction()
        y = event.getY()
        if (mStateTV != null && mStateIV != null && y < 0) {
            mStateTV?.setText("取消")
            mStateIV?.setImageDrawable(resources.getDrawable(R.drawable.ic_volume_cancel))
        } else if (mStateTV != null) {
            mStateTV?.setText("取消")
        }
        when (action) {
            MotionEvent.ACTION_DOWN -> {
                setText("松开发送")
                initDialogAndStartRecord()
            }

            MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                this.setText("开始说话")
                if (y >= 0) {
                    if ((System.currentTimeMillis() - startTime <= MAX_INTERVAL_TIME)) {
                        error("结束录音:")
                        finishRecord()
                    }
                } else if (y < 0) {  //当手指向上滑，会cancel
                    cancelRecord()
                }
            }
        }

        return true
    }

    /**
     * 初始化录音对话框 并 开始录音
     */
    private fun initDialogAndStartRecord() {
        startTime = System.currentTimeMillis()
        recordDialog = Dialog(getContext(), R.style.like_toast_dialog_style)
        recordDialog?.requestWindowFeature(Window.FEATURE_NO_TITLE)
        // 设置对话框背景为透明
        recordDialog?.getWindow()?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        view = inflate(getContext(), R.layout.dialog_record, null)
        mStateIV = view?.findViewById<View?>(R.id.rc_audio_state_image) as? ImageView
        mStateTV = view?.findViewById<View?>(R.id.rc_audio_state_text) as? TextView
        mStateIV?.setImageDrawable(getResources().getDrawable(R.drawable.anim_mic))
        anim = mStateIV?.getDrawable() as AnimationDrawable
        anim?.start()
        mStateIV?.setVisibility(VISIBLE)
        mStateTV?.setVisibility(VISIBLE)
        mStateTV?.setText("手指上滑,取消发送")
        recordDialog!!.setContentView(view!!, LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT))
        recordDialog!!.setOnDismissListener(onDismiss)
        val lp = recordDialog?.getWindow()?.getAttributes()
        lp?.gravity = Gravity.CENTER
        startRecording()
        recordDialog?.show()
    }

    /**
     * 放开手指，结束录音处理
     */
    private fun finishRecord() {
        val intervalTime: Long = System.currentTimeMillis() - startTime
        if (intervalTime < MIN_INTERVAL_TIME) {
            error("录音时间太短")
            volumeHandler?.sendEmptyMessageDelayed(-100, 500)
            mStateIV?.setImageDrawable(getResources().getDrawable(R.drawable.ic_volume_wraning))
            mStateTV?.setText("时间太短")
            anim?.stop()
            cancelRecord()
            return
        } else {
            val path = stopRecording()
            recordDialog?.dismiss()
            error("录音完成的路径:" + path)
            val mediaPlayer = MediaPlayer()
            try {
                mediaPlayer.setDataSource(path)
                mediaPlayer.prepare()
                mediaPlayer.getDuration()
                error("获取到的时长:" + mediaPlayer.duration / 1000)
            } catch (e: Exception) {
            }
            finishedListener?.onFinishedRecord(path, mediaPlayer.getDuration())
        }

    }

    /**
     * 取消录音对话框和停止录音
     */
    fun cancelRecord() {
        val path = stopRecording()
        recordDialog?.dismiss()
        File(path).also {
            it.delete()
        }
    }


    //5分钟
    var timer: ZCountDownTimer = object : ZCountDownTimer((MAX_INTERVAL_TIME + 10).toLong(), 1000) {
        public override fun onFinish() {
            finishRecord()
        }

        public override fun onTick(millisUntilFinished: Long) {
        }
    }

    /**
     * 执行录音操作
     */
    private fun startRecording() {
        timer.restart()
        mRecorder.startRecording()
    }


    private fun stopRecording(): String {
        return mRecorder.stopRecording()
    }


    private val onDismiss: DialogInterface.OnDismissListener = object : DialogInterface.OnDismissListener {
        override fun onDismiss(dialog: DialogInterface?) {
            stopRecording()
        }
    }

    interface OnFinishedRecordListener {
        /**
         *
         * @param audioPath
         * @param time 毫秒
         */
        fun onFinishedRecord(audioPath: String, time: Int)
    }


    companion object {
        private var view: View? = null
        private var startTime: Long = 0
        private val res = intArrayOf(
            R.drawable.ic_volume_0,
            R.drawable.ic_volume_1,
            R.drawable.ic_volume_2,
            R.drawable.ic_volume_3,
            R.drawable.ic_volume_4,
            R.drawable.ic_volume_5,
            R.drawable.ic_volume_6,
            R.drawable.ic_volume_7,
            R.drawable.ic_volume_8
        )
    }
}
